<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="header-container">
          <!-- 左侧图标 -->
          <div class="nav-icon" @click="handleIconClick">
            <el-icon :size="28">
              <House />
            </el-icon>
          </div>

          <!-- 中间菜单区域 -->
          <el-menu :default-active="activeMenu" mode="horizontal" @select="handleSelect" router class="main-menu">
            <!-- <el-menu-item index="logo">
              <img style="width: 100px" src="@/assets/logo/logo.jpg" alt="Logo" />
            </el-menu-item> -->

            <el-menu-item index="/home" @click="setActive('/home')">首页</el-menu-item>

            <el-menu-item index="/map" @click="setActive('/map')">地图</el-menu-item>
            <el-menu-item index="/chat" @click="setActive('/chat')">AI助手</el-menu-item>
            <el-menu-item index="/activity" @click="setActive('/activity')">活动审批</el-menu-item>

            <el-sub-menu index="/tree" @click="setActive('/tree')">

              <template #title>
                <span :class="{ 'active-submenu': activeMenu.startsWith('/tree') }">古树管理</span>
              </template>
              <el-menu-item index="/treeInfo" @click="setActive('/treeInfo')"
                :class="{ 'active-subitem': activeMenu === '/treeInfo' }">
                古树信息
              </el-menu-item>
              <el-menu-item index="/addTree" @click="setActive('/addTree')"
                :class="{ 'active-subitem': activeMenu === '/addTree' }">
                添加古树
              </el-menu-item>
              <el-menu-item index="/issue" @click="setActive('/issue')"
                :class="{ 'active-subitem': activeMenu === '/issue' }">
                古树异常信息
              </el-menu-item>
            </el-sub-menu>

          </el-menu>

          <!-- 右侧用户区域 -->
          <div class="user-area">
            <template v-if="!isLoggedIn">
              <el-button link @click="showLoginDialog">登录</el-button>
              <el-button link @click="showRegisterDialog">注册</el-button>
            </template>
            <template v-else>
              <el-dropdown @command="handleUserCommand">
                <div class="user-avatar">
                  <el-avatar :size="36" :src="userInfo.avatar" />
                  <span class="user-name">{{ userInfo.name }}</span>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="personalCenter">个人中心</el-dropdown-item>
                    <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
                    <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </div>
        </div>
      </el-header>

      <el-main>
        <router-view />
      </el-main>
      <!-- 登录对话框 -->
      <el-dialog v-model="loginVisible" title="登录" width="30%" class="login-dialog">
        <div class="login-container">
          <!-- 卡片风格选项卡 -->
          <el-tabs v-model="loginType" class="login-tabs" stretch>
            <el-tab-pane label="密码登录" name="password">
              <el-form :model="loginForm" label-width="80px" style="margin-top: 20px;">
                <el-form-item label="手机号">
                  <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="验证码登录" name="captcha">
              <el-form :model="loginForm" label-width="80px" style="margin-top: 20px;">
                <el-form-item label="手机号">
                  <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="验证码">
                  <el-input v-model="loginForm.captcha" placeholder="请输入验证码">
                    <template #append>
                      <el-button @click="sendVerificationcaptcha" :disabled="countdown > 0">
                        {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>

          <!-- 登录按钮 -->
          <div class="login-footer">
            <el-button type="primary" @click="handleLogin" style="width: 100%; height: 42px; font-size: 16px;"
              :loading="loginLoading">
              登 录
            </el-button>
          </div>
        </div>
      </el-dialog>


      <!-- 注册对话框 -->
      <!-- 注册对话框 -->
      <el-dialog v-model="registerVisible" title="注册" width="30%" class="register-dialog">
        <div class="register-container">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
            </el-form-item>

            <el-form-item label="验证码" prop="captcha">
              <el-input v-model="registerForm.captcha" placeholder="请输入验证码">
                <template #append>
                  <el-button @click="sendRegisterCaptcha" :disabled="registerCountdown > 0">
                    {{ registerCountdown > 0 ? `${registerCountdown}秒后重发` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>

          <div class="register-footer">
            <el-button type="primary" @click="handleRegister" style="width: 100%; height: 42px; font-size: 16px;"
              :loading="registerLoading">
              注 册
            </el-button>
          </div>
        </div>
      </el-dialog>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { House } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { passwordLogin, captchaLogin, sendCaptcha, register } from '@/apis/authAPI'
import { useAuthStore } from '@/stores/auth/userAuthStore'

const route = useRoute()
const router = useRouter()
const countdown = ref(0) // 倒计时秒数，0 表示可以重新发送
const authStore = useAuthStore()

// 用户登录状态
const isLoggedIn = computed(() => authStore.isAuthenticated)

// 用户信息 
const userInfo = computed(() => ({
  name: authStore.user?.nickname || '',
  avatar: authStore.user?.avatar || ''
}))

// 登录表单 
const loginForm = ref({
  phone: '',     // 手机号
  password: '',
  captcha: ''    // ：验证码
})

const loginType = ref('password') // 'password' 表示密码登录，'code' 表示验证码登录

// 注册倒计时
const registerCountdown = ref(0)

// 注册loading状态
const registerLoading = ref(false)

// 注册表单引用
const registerFormRef = ref()

// 注册表单
const registerForm = reactive({
  phone: '',
  password: '',
  confirmPassword: '',
  captcha: ''
})

// 注册表单验证规则
const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
      message: '密码至少包含一个字母和一个数字，长度为6-20位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' }
  ]
}
// 发送注册验证码
const sendRegisterCaptcha = async () => {
  if (!registerForm.phone) {
    ElMessage.error('请输入手机号')
    return
  }

  // 验证手机号格式
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(registerForm.phone)) {
    ElMessage.error('手机号格式不正确')
    return
  }

  if (registerCountdown.value > 0) {
    ElMessage.info(`请等待 ${registerCountdown.value} 秒后再重新发送`)
    return
  }

  try {
    const result = await sendCaptcha({ phone: registerForm.phone })

    if (result.code === 1) {
      ElMessage.success('验证码已发送，请查收短信')
      registerCountdown.value = 60
      const timer = setInterval(() => {
        registerCountdown.value--
        if (registerCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      ElMessage.error(result.msg || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('网络请求出错，请重试')
    console.error(error)
  }
}
// 处理注册
const handleRegister = async () => {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      registerLoading.value = true
      const { phone, password, captcha } = registerForm

      // 调用注册接口
      const result = await register({ phone, password, captcha })

      if (result.code === 1) {
        ElMessage.success('注册成功，请登录')
        registerVisible.value = false

        // 重置表单
        registerFormRef.value.resetFields()
        // 注册成功后打开登录弹窗
        loginVisible.value = true

      } else {
        ElMessage.error(result.msg || '注册失败')
      }
    } catch (error) {
      ElMessage.error('网络请求出错，请重试')
      console.error(error)
    } finally {
      registerLoading.value = false
    }
  })
}

// 对话框可见性
const loginVisible = ref(false)
const registerVisible = ref(false)

// 登录loading状态
const loginLoading = ref(false)

// 当前激活菜单 
const activeMenu = ref(route.path)

// 显示登录对话框
const showLoginDialog = () => {
  loginVisible.value = true
}

// 显示注册对话框
const showRegisterDialog = () => {
  registerVisible.value = true
}

//发送验证码
// 发送验证码方法
const sendVerificationcaptcha = async () => {
  const phone = loginForm.value.phone;

  if (!phone) {
    ElMessage.error('请输入手机号');
    return;
  }

  if (countdown.value > 0) {
    ElMessage.info(`请等待 ${countdown.value} 秒后再重新发送`);
    return;
  }

  try {
    // 调用发送验证码接口
    const result = await sendCaptcha({ phone });

    if (result.code === 1) {
      ElMessage.success('验证码已发送，请查收短信');
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error(result.msg || '验证码发送失败');
    }
  } catch (error) {
    ElMessage.error('网络请求出错，请重试');
    console.error(error);
  }
};

// 处理登录
const handleLogin = async () => {
  const { phone, password, captcha } = loginForm.value;

  // 验证手机号格式
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!phoneReg.test(phone)) {
    ElMessage.error('手机号格式不正确');
    return;
  }

  if (loginType.value === 'password') {
    // 密码登录：验证密码格式
    const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
    if (!passwordReg.test(password)) {
      ElMessage.error('密码至少包含一个字母和一个数字，长度为6-20位');
      return;
    }
  } else {
    // 验证码登录：验证验证码格式
    const codeReg = /^\d{6}$/;
    if (!codeReg.test(captcha)) {
      ElMessage.error('验证码格式不正确');
      return;
    }
  }

  try {
    loginLoading.value = true; // 开启loading状态
    let result;
    if (loginType.value === 'password') {
      result = await passwordLogin({ phone, password });
    } else {
      result = await captchaLogin({ phone, captcha: captcha });
    }

    if (result.code === 1) {
      isLoggedIn.value = true;
      userInfo.value.name = phone;
      loginVisible.value = false;
      loginForm.value = { phone: '', password: '', captcha: '' };
      //将登录信息保存到store中
      authStore.loginSuccess(result.data)
      ElMessage.success('登录成功');
      userInfo.value.avatar = result.data.avatar
      userInfo.value.name = result.data.nickname

    } else {
      ElMessage.error(result.message || '登录失败');
      loginForm.value = { phone: '', password: '', captcha: '' };
    }
  } catch (error) {
    ElMessage.error('网络请求出错，请重试');
    console.error(error);
  } finally {
    loginLoading.value = false; // 关闭loading状态
  }
};
// 处理用户命令 
const handleUserCommand = (command) => {
  switch (command) {
    case 'personalCenter':
      router.push('/personalCenter')
      break
    case 'updatePassword':
      router.push('/updatePassword')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理退出登录
const handleLogout = () => {
  // 添加二次确认
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '退出登录',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    authStore.logout(); // 清除状态和 localStorage
    router.push('/home')
    ElMessage.success('已退出登录')
  }).catch(() => {
    // 用户取消操作
  })
}

// 设置当前激活菜单
const setActive = (path) => {
  activeMenu.value = path
}

// 处理菜单选择 
const handleSelect = (index) => {
  activeMenu.value = index
}

// 处理图标点击
const handleIconClick = () => {
  router.push('/home')
  setActive('/home')
}
</script>

<style scoped>
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  padding: 0;
  height: auto;
  border-bottom: 1px solid #eee;
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  position: relative;
}

/* 左侧图标样式 */
.nav-icon {
  margin-left: 20px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.nav-icon:hover {
  color: #409EFF;
}

/* 中间菜单区域 */
.main-menu {
  flex: 1;
  display: flex;
  justify-content: center;
  border-bottom: none !important;
}

/* 右侧用户区域 */
.user-area {
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-name {
  margin-left: 8px;
  font-size: 14px;
}

/* 菜单项样式 */
.el-menu-item.is-active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.active-submenu {
  color: #409EFF;
}

.active-subitem {
  color: #409EFF;
  background-color: #ecf5ff;
}

.el-radio-group {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 4px;
  background-color: #f5f7fa;
}

.el-radio {
  margin: 0 10px;
}

.el-radio.is-checked {
  background-color: #409EFF;
  color: white !important;
}

.login-dialog {
  text-align: center;
}

.login-container {
  padding: 0 20px 20px;
}

.login-title {
  margin: 0 0 24px;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

/* 选项卡样式 */
.login-tabs {
  margin-bottom: 24px;
}

.login-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.login-tabs :deep(.el-tabs__nav) {
  width: 100%;
  display: flex;
}

.login-tabs :deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
  padding: 0 16px;
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  transition: all 0.3s;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #409EFF;
  font-weight: 500;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #409EFF;
  height: 3px;
}

.login-footer {
  padding: 0 20px;
}

.register-dialog {
  text-align: center;
}

.register-container {
  padding: 0 20px 20px;
}

.register-footer {
  padding: 0 20px;
}
</style>